package com.example.myproject.tracker;

import com.example.myproject.exception.BusinessException;
import com.turn.ttorrent.tracker.TrackedTorrent;
import com.turn.ttorrent.tracker.Tracker;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.util.UUID;

@Component
public class TrackerManager  {
    private Tracker tracker;

    @PostConstruct
    public void startTracker() {
        try {
            tracker = new Tracker(6969);
            tracker.setAcceptForeignTorrents(true);
            new Thread(() -> {
                try {
                    tracker.start(false); // 非阻塞
                    System.out.println("Tracker 启动成功，监听端口 6969");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
        } catch (Exception e) {
            System.err.println("Tracker 启动失败");
            e.printStackTrace();
        }
    }

    public void registerTorrent(File torrentFile) {
        try {
            TrackedTorrent torrent = TrackedTorrent.load(torrentFile);
            tracker.announce(torrent);
            System.out.println("种子注册成功：" + torrentFile.getName());
        } catch (Exception e) {
            System.err.println(" 种子注册失败：" + torrentFile.getName());
            e.printStackTrace();
        }
    }
}